<!--
*@Author: QWP
*@Description: 公共的人员选择弹窗
*@Date 2024-09-09 15:19
-->
<template>
  <u-dialog :title="$attrs['title'] || '人员选择'"
    v-bind="$attrs"
    wrap-class-name="full-modal"
    destroyOnClose
    @submit="submit"
    @close="dialogClose"
  >
    <a-layout class="f-h-100">
      <u-collapsed-sider width="350px"
        :canExpand="false"
        style="overflow: auto;">
        <u-tree :treeData="treeData"
          :checkable="multiple"
          :showSearch="false"
          :fieldNames="{
            title: 'name',
            key: 'keyid',
            children: 'children',
          }"
          v-model:expandedKeys ="expandedKeys"
          v-model:checkedKeys="checkedKeys"
          v-model:selectedKeys="selectedKeys"
          v-bind="treeProps"
          class="u-commit-audit-tree"
          v-if="refresh"
          @check="treeCheck"
          @select="treeSelect"
        >
        </u-tree>
      </u-collapsed-sider>
      <a-layout>
        <u-table-header v-if="showTip">
          <a-row style="font-size: 16px; color: #333333;">
            <slot name="tipText"></slot>
          </a-row>
        </u-table-header>
        <u-table-content ref="tabContentRef">
          <u-table :columns="columns"
            :data="tabData"
            v-bind="tableProps"
            :rowSelection="null"
            :scroll="{ y: 'calc(100vh - 230px)' }"
          ></u-table>
        </u-table-content>
      </a-layout>
    </a-layout>
    <template #footerBefore>
      
    </template>
  </u-dialog>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'u-sel-user'
})
import { ref, reactive, useAttrs, watch, onMounted, h, computed, nextTick, isRef } from "vue";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { storeToRefs } from "pinia";
import { useLoginStore, useBaseStore } from "@/store";
import {
  Button,
  Popconfirm,
  TableColumnProps,
} from "ant-design-vue";
import { cloneDeep } from "lodash";
import UIconFont from '@/components/common/iconfont/IconFont.vue'
import { nullC } from '@/util/common'
import { getItemByIds, debounce, throttle } from '@/util/format.ts'
import * as travelApi from "@/service/administration/travel";
import * as roleApi from '@/service/system/role'
import { evectionUserTree } from '@/service/administration/travel'
import { useTableScroll } from '@/hooks/useTable'

const props = withDefaults(defineProps<{
  selData?: string | string[],
  isLoadData?: boolean,
  treeProps?: object,
  tableProps?: object,
  showTip?: boolean,
  filterParent?: boolean,
  multiple?: boolean,
  parent?: objetc
}>(), {
  selData: [],
  treeProps: {},
  tableProps: {},
  showTip: false,
  isLoadData: true,
  filterParent: true,
  multiple: true,
  parent: { 
    key: 'deptname', 
    valueKey: 'fkparentid', 
    parentTLable: '所在部门'
  }
})

const attrs = useAttrs()

const checkedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);

const emits = defineEmits(["submit", 'change']);

const { userInfo } = storeToRefs(useLoginStore());
const { deptUsers, deptData } = storeToRefs(useBaseStore());
const formLoading = ref<boolean>(false);

// 初始化表格
const tabData = ref<any[]>([])
let columns: Array<TableColumnProps> = reactive([
  { dataIndex: "index", title: "序号", align: "center", width: 100,
    customRender: ({ index }) => index += 1
  },
  // { dataIndex: props.parent.key, title: props.parent.parentTLable, align: "center" },
  { dataIndex: "name", title: "姓名", },
  {
    dataIndex: "remove",
    title: "操作",
    width: 100,
    align: "center",
    customRender: ({ record, text, index }) => {
      return h(UIconFont, { 
        type: 'icon-a-shanchu1', 
        style: {color: '#1890ff'},
        onClick: () => {
          tabData.value.splice(index, 1);
          props.multiple == true ? checkedKeys.value.splice(index, 1) : selectedKeys.value.splice(index, 1);
          refreshTree()
        }
      });
    },
  },
]);

// 获取部门人员数据
const refresh = ref<boolean>(true)
const getExtraData = computed(() => {
  let tExData = cloneDeep(attrs['extraData'] || [])
  return isRef(tExData) ? tExData.value : tExData 
})
const treeData = computed(() => {
  let tExData = attrs['extraData'] || []
  return [ ...getExtraData.value, ...(props.isLoadData == true ? deptUsers.value : []) ]
})
const deptIds = computed(() => {
  if(props.isLoadData == true) {
    return (deptData.value || []).map(i => i.keyid)
  } else {
    return getExtraData.value.map(i => i.keyid)
  }
})

// 树形勾选事件
function treeCheck(keys, {checked, checkedNodes, node, event }) {
  let checkedNodes1 = cloneDeep(checkedNodes)
  if(props.filterParent) {
    checkedNodes1 = checkedNodes1.filter(i => (i['children'] || []).length == 0)
  }
  checkedNodes1.forEach(i => {
    delete i['children']
  })
  tabData.value = checkedNodes1
}

// 树形点击事件
function treeSelect(selectedKeys, {selected, selectedNodes, node, event}) {
  if (props.multiple == true) return;
  if(props.filterParent && (selectedNodes[0]['children'] || []).length != 0) {
    return
  } 
  let selectedNodes1 = cloneDeep(selectedNodes)
  delete selectedNodes1[0]['children']
  tabData.value = selectedNodes1
}

// 确认提交
const submit = () => {
  let tData = cloneDeep(tabData.value);
  if(props.filterParent == true) {
    tData = tData.filter(o => !deptIds.value.includes(o.keyid))
  }
  emits("submit", cloneDeep(tabData.value));
  emits("change", cloneDeep(tabData.value));

  dialogClose()
};

// 回显选中的数据
const echoInfo = () =>{
  let tSelData = cloneDeep(props.selData)
  if(typeof tSelData == 'string') {
    tSelData = tSelData.split(',')
  }
  props.multiple == true ? checkedKeys.value = tSelData : selectedKeys.value = tSelData

  let tTabData = cloneDeep(getItemByIds(treeData.value, Array.from(new Set(tSelData))))
  tTabData.forEach(i => {
    delete i['children']
  })
  tTabData.forEach(item => {
    if(!tabData.value.some(i => i.keyid == item.keyid)) {
      tabData.value.push(item)
    }
  })
}


// 获取父级名称
const getDeptName = (fkparentid: string) => {
  let info = treeData.value.find(o => o.keyid == fkparentid) || {};
  return nullC(info['name'])
}

// 刷新树
let timer = null;
const refreshTree = () => {
  refresh.value = false;
  nextTick(() => {
    refresh.value = true;
  })
}

watch(() => attrs.open, (nval, oval) => {
  if(nval == true) {
    echoInfo()
  }
}, { immediate: true, deep: true })

// 弹窗关闭
const dialogClose = () => {
  checkedKeys.value = [];
  selectedKeys.value = [];
  expandedKeys.value = [];
  tabData.value = [];
}

</script>

<style lang="scss"></style>
